<template>
    <div class="profile-container">
        <!-- 顶部背景 -->
        <div class="profile-banner"></div>
        <div class="profile-main">
            <!-- 头像 -->
            <div class="profile-avatar">
                <AvatarUpload
                    :initial="userNameInitial"
                    v-model:imageUrl="userInfo.userAvatar"
                    @file-change="handleAvatarChange"
                />
            </div>
            <!-- 用户名 -->
            <div class="profile-info">
                <h1 class="profile-username">{{ userInfo.userName || userInfo.userAccount }}</h1>
                <div class="profile-actions">
                    <button class="edit-btn" @click="toggleEditMode">
                        {{ isEditing ? '保存' : '编辑资料' }}
                    </button>
                    <!-- <button class="password-btn" @click="handleChangePassword">
                        {{ isEditing ? '取消' : '修改密码' }}
                    </button> -->
                </div>
            </div>
        </div>
        <!-- 个人信息展示/编辑区域 -->
        <div class="profile-section">
            <div v-if="!isEditing" class="profile-details">
                <div class="detail-row">
                    <span class="detail-label">账号：</span>
                    <span class="detail-value">{{ userInfo.userAccount }}</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">用户名：</span>
                    <span class="detail-value">{{ userInfo.userName || '未设置' }}</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">个人简介：</span>
                    <span class="detail-value">{{ userInfo.userProfile || '未设置' }}</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">用户角色：</span>
                    <span class="detail-value">{{
                        userInfo.userRole === 'admin' ? '管理员' : '普通用户'
                    }}</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">账户余额：</span>
                    <span class="detail-value">¥{{ userInfo.balance }}</span>
                </div>
            </div>
            <div v-else class="edit-form">
                <div class="edit-row">
                    <label>用户名</label>
                    <el-input v-model="userInfo.userName" placeholder="请输入用户名" />
                </div>
                <div class="edit-row">
                    <label>个人简介</label>
                    <el-input
                        v-model="userInfo.userProfile"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入个人简介"
                    />
                </div>
            </div>
        </div>
        <!-- 订单信息展示区域 -->
        <div class="orders-section">
            <OrderList :orders="purchaseOrders" :loading="loading" />
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { listUserByPage, updateMyUser } from '@/api/user'
import { listOrderByPage } from '@/api/order'
import { ElMessage } from 'element-plus'
import AvatarUpload from '@/components/AvatarUpload.vue'
import OrderList from '@/components/OrderList.vue'

const userInfo = ref({
    id: '',
    userAccount: '',
    userName: '',
    userAvatar: '',
    userProfile: '',
    userRole: '',
    balance: '0'
})

const userNameInitial = computed(() =>
    userInfo.value.userName
        ? userInfo.value.userName[userInfo.value.userName.length - 1]
        : userInfo.value.userAccount
          ? userInfo.value.userAccount[userInfo.value.userAccount.length - 1]
          : ''
)

const isEditing = ref(false)
console.log('userInfo', userInfo.value)
// 获取用户信息
const getUserInfo = () => {
    const userId = localStorage.getItem('token')
    if (!userId) {
        ElMessage.error('未登录')
        return
    }

    listUserByPage({
        current: 1,
        pageSize: 1,
        id: userId
    })
        .then(res => {
            if (res.code === 0 && res.data.records && res.data.records.length > 0) {
                const userData = res.data.records[0]
                userInfo.value = {
                    id: userData.id || '',
                    userAccount: userData.userAccount || '',
                    userName: userData.userName || '',
                    userAvatar: userData.userAvatar || '',
                    userProfile: userData.userProfile || '',
                    userRole: userData.userRole || '',
                    balance: userData.balance ?? 0
                }
                console.log('userData', userData)
                localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
            } else {
                ElMessage.error('获取用户信息失败')
            }
        })
        .catch(error => {
            ElMessage.error(error.message || '获取用户信息失败')
        })
}

// 处理头像上传
const handleAvatarChange = async url => {
    try {
        userInfo.value.userAvatar = url
        await saveUserInfo()
        ElMessage.success('头像更新成功')
    } catch (error) {
        ElMessage.error('头像更新失败')
    }
}

// 保存用户信息
const saveUserInfo = () => {
    const updateData = {
        id: userInfo.value.id,
        userName: userInfo.value.userName,
        userProfile: userInfo.value.userProfile,
        userAvatar: userInfo.value.userAvatar
    }

    updateMyUser(updateData)
        .then(res => {
            if (res.code === 0) {
                ElMessage.success('保存成功')
                isEditing.value = false
            } else {
                ElMessage.error(res.message || '保存失败')
            }
        })
        .catch(error => {
            ElMessage.error(error.message || '保存失败')
        })
}

const purchaseOrders = ref([])
const loading = ref(false)

// 获取订单列表
const fetchOrders = async () => {
    loading.value = true
    try {
        const res = await listOrderByPage({
            current: 1,
            pageSize: 999,
            payerid: userInfo.value.id
        })
        if (res.code === 0) {
            purchaseOrders.value = res.data.records.map(order => ({
                orderId: order.id,
                goods: order.name,
                amount: order.num,
                total: `¥${order.price * order.num}`
            }))
        } else {
            ElMessage.error(res.message || '获取订单列表失败')
        }
    } catch (error) {
        ElMessage.error(error.message || '获取订单列表失败')
    } finally {
        loading.value = false
    }
}

// 页面加载时获取用户信息和订单列表
onMounted(() => {
    getUserInfo()
    fetchOrders()
})

const toggleEditMode = () => {
    if (isEditing.value) {
        saveUserInfo()
    } else {
        isEditing.value = true
    }
}

// const handleChangePassword = () => {
//     if (!isEditing.value) {
//         // TODO: 实现修改密码逻辑
//         ElMessage.info('修改密码功能开发中')
//     } else {
//         isEditing.value = false
//     }
// }
</script>

<style lang="less" scoped>
.profile-container {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    margin: 40px auto;
    overflow: hidden;
    font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
    display: flex;
    flex-direction: column;
}

.profile-banner {
    height: 120px;
    background: linear-gradient(90deg, #4caf50 60%, #76c7c0 100%);
}

.profile-main {
    display: flex;
    flex-wrap: wrap;
    align-items: flex-end;
    padding: 0 32px;
    position: relative;
    top: -48px;
    gap: 24px;
}

.profile-avatar {
    flex-shrink: 0;
    margin-right: 32px;
}

.profile-info {
    flex: 1;
    min-width: 300px;
    padding-bottom: 18px;
    display: flex;
    flex-direction: column;
    gap: 12px;

    .profile-username {
        font-size: 2.2rem;
        font-weight: 700;
        margin: 0 0 6px 0;
        color: #222;
    }

    .profile-actions {
        display: flex;
        gap: 12px;
        margin-top: 8px;

        .edit-btn,
        .password-btn {
            padding: 6px 20px;
            font-size: 1rem;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background 0.2s;
        }

        .edit-btn {
            background: #4caf50;
            color: #fff;

            &:hover {
                background: #388e3c;
            }
        }

        .password-btn {
            background: #ff9800;
            color: #fff;

            &:hover {
                background: #e68900;
            }
        }
    }
}

.profile-section {
    padding: 32px;
    border-top: 1px solid #f0f0f0;
}

.profile-details {
    display: flex;
    flex-direction: column;
    gap: 16px;

    .detail-row {
        display: flex;
        align-items: center;
        font-size: 16px;
        line-height: 1.5;

        .detail-label {
            width: 120px;
            color: #666;
            font-weight: 500;
        }

        .detail-value {
            color: #333;
        }
    }
}

.edit-form {
    display: flex;
    flex-direction: column;
    gap: 20px;

    .edit-row {
        display: flex;
        align-items: center;

        label {
            width: 120px;
            color: #555;
            font-weight: 500;
            font-size: 16px;
        }

        .el-input {
            flex: 1;
        }
    }
}

.orders-section {
    padding: 32px;
    border-top: 1px solid #f0f0f0;
    display: flex;
    flex-direction: column;
    flex: 1;
}
</style>
